package com.menghanjun.mhjresourcesharing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.menghanjun.mhjresourcesharing.entity.TBar;
import com.menghanjun.mhjresourcesharing.entity.TResources;
import com.menghanjun.mhjresourcesharing.mapper.TBarMapper;
import com.menghanjun.mhjresourcesharing.mapper.TResourcesMapper;
import com.menghanjun.mhjresourcesharing.service.ITResourcesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.menghanjun.mhjresourcesharing.utils.CombinedIdGenerator;
import com.menghanjun.mhjresourcesharing.utils.JsonResponseBody;
import com.menghanjun.mhjresourcesharing.utils.JsonResponseStatus;
import com.menghanjun.mhjresourcesharing.utils.Utils;
import com.menghanjun.mhjresourcesharing.vo.TResourcesVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author menghanjun
 * @since 2024-04-19
 */
@Service
@Slf4j
public class TResourcesServiceImpl extends ServiceImpl<TResourcesMapper, TResources> implements ITResourcesService {


    @Autowired
    private TResourcesMapper resourcesMapper;

    @Autowired
    private TBarMapper barMapper;

    /**
     * 获取资源列表
     * @param type
     * @param title
     * @param resourceId
     * @param level
     * @param pageNo
     * @param pageSize
     * @param order
     * @param queryFlag  是否是主页查询
     * @return
     */
    @Override
    public List<TResourcesVo> getResourcesList(String type,String title,String resourceId,String level,int pageNo, int pageSize,String order,String queryFlag) {
        List<TResourcesVo> ls = new ArrayList<>();
        try {
            if(StringUtils.isEmpty(order)){
                order = "created_at";
            }else if(order.equals("T")){
                order = "created_at";
            }else if(order.equals("C")){
                order = "click_count";
            }
            if(StringUtils.isEmpty(queryFlag)){
                queryFlag = "N";
            }
            int offset = (pageNo - 1) * pageSize;
            if("Y".equals(queryFlag)){//调用主页查询专用方法
                ls = resourcesMapper.queryResourcesList(type,title,resourceId,level,offset,pageSize,order);
            }else{
                ls = resourcesMapper.getResourcesList(type,title,resourceId,level,offset,pageSize,order);
            }

            if(type!=null&&!type.equals("文案哲理")&&!type.equals("其它工具")){
                ls.forEach(tResourcesVo -> {
                    String htmlString = tResourcesVo.getDescription();
                    String plainText = htmlString.replaceAll("\\<.*?\\>", "");
                    tResourcesVo.setDescription(plainText);
                });
            }
        } catch (Exception e) {
            log.error("getResourcesList报错！"+e.getMessage());
        }
        return ls;
    }

    @Override
    public int getResourcesListTotal(String type, String title,String resourceId,String level,String queryFlag) {
        if(StringUtils.isEmpty(queryFlag)){
            queryFlag = "N";
        }
        if("Y".equals(queryFlag)){//调用主页查询专用方法
            return resourcesMapper.queryResourcesListTotal(type,title,resourceId,level);
        }
        return resourcesMapper.getResourcesListTotal(type, title,resourceId,level);
    }

    /**
     * 根据资源ID获取Url
     * @param id
     * @return
     */
    @Override
    public String getResourceUrlById(String id) {
        String url = "";
        try {
            QueryWrapper<TResources> wrapper = new QueryWrapper<>();
            wrapper.eq("resource_id",id);
            TResources tResources = resourcesMapper.selectOne(wrapper);
            if(tResources!=null){
                url = tResources.getUrl();
            }
        } catch (Exception e) {
            log.error("getResourceUrlById报错！"+e.getMessage());
        }
        return url;
    }

    /**
     * 根据ID查询资源
     * @param resourceId
     * @return
     */
    @Override
    public TResources getResourceById(String resourceId) {
        try {
            QueryWrapper<TResources> wrapper = new QueryWrapper<>();
            wrapper.eq("resource_id",resourceId);
            TResources tResources = resourcesMapper.selectOne(wrapper);
            return tResources;
        }catch (Exception e){
            log.error("getResourceById报错！"+e.getMessage());
        }
        return null;
    }


    /**
     * 根据ID查询资源
     * @param resourceId
     * @return
     */
    @Override
    public TResourcesVo getResourceVoById(String resourceId) {
        try {
            TResourcesVo tResources = resourcesMapper.getResourceVoById(resourceId);
            return tResources;
        }catch (Exception e){
            log.error("getResourceById报错！"+e.getMessage());
        }
        return null;
    }



    @Override
    public void updateResource(TResources resources) {
        if(resources.getCover()!=null&&resources.getCover().indexOf("tmp")!=-1){//说明更改了封面，将临时图片拷贝到原封面位置
            String projectPath = System.getProperty("user.dir"); // 获取当前项目的路径
            File projectFile = new File(projectPath); // 构建项目路径的 File 对象
            String projectDrive = projectFile.getParentFile().getAbsolutePath(); // 获取项目所在盘符的绝对路径
            String ext = resources.getCover().substring(resources.getCover().lastIndexOf("."),resources.getCover().length());//拿到文件后缀
            String tmpPath = projectDrive + "/resources/tmp/"+resources.getResourceId()+ext;
            String converPath = projectDrive + "/resources/cover/"+resources.getResourceId();//删除原封面
            try {
                File coverFolder = new File(converPath);
                if(!coverFolder.exists()){
                    coverFolder.mkdirs();
                }
                // 创建 File 对象
                File folder = new File(converPath);
                // 获取文件夹下所有文件
                File[] files = folder.listFiles();
                // 遍历文件并删除
                if (files != null) {
                    for (File file : files) {
                        if (file.isFile()) {
                            file.delete(); // 删除文件
                        }
                    }
                }
                InputStream inputStream = new FileInputStream(new File(tmpPath));
                OutputStream outputStream = new FileOutputStream(new File(converPath+"/"+resources.getResourceId()+ext));
                Utils.copyFile(inputStream, outputStream);
                inputStream.close();
                outputStream.close();
                //删除临时文件
                File tmpFile = new File(tmpPath);
                tmpFile.delete();
            } catch (Exception e) {
                log.error("updateResource报错！"+e.getMessage());
            }
            //设置新的封面
            resources.setCover("/resourcesharing/img/cover/"+resources.getResourceId()+"/"+resources.getResourceId()+ext);
        }
        resourcesMapper.updateResource(resources);
    }

    @Override
    public void thoroughDeleteResourceById(String resourceId) {
        resourcesMapper.delete(new QueryWrapper<TResources>().eq("resource_id",resourceId));
    }

    @Override
    public String uploadResourceImage(MultipartFile files, String resourceId) {
        String imageUrl = "";
        try {
            String imageName = CombinedIdGenerator.generateId()+"";
            File uploadfile = null;
            String projectPath = System.getProperty("user.dir"); // 获取当前项目的路径
            File projectFile = new File(projectPath); // 构建项目路径的 File 对象
            String projectDrive = projectFile.getParentFile().getAbsolutePath(); // 获取项目所在盘符的绝对路径
            // 获取文件的原始名称
            String ext = files.getOriginalFilename();
            ext = ext.substring(ext.lastIndexOf("."),ext.length());//拿到文件后缀
            if(!ext.toLowerCase().equals(".png")&&!ext.toLowerCase().equals(".jpg")&&!ext.toLowerCase().equals(".jpeg"))  {
                return "typeerr";
            }
            // 设置文件上传的路径
            String url  = projectDrive+"/resources/"+resourceId;
            uploadfile = new File(url + "/" + imageName + ext);
            File file = new File(url);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 以绝对路径保存重命名后的文件
            files.transferTo(uploadfile);
            imageUrl = "/resourcesharing/img/"+resourceId+"/"+imageName+ext;
            System.out.println(url + "/" + imageName + ext);
        } catch (Exception e) {
            log.error("uploadResourceImage报错！"+e.getMessage());
        }
        return imageUrl;
    }

    @Override
    public boolean isResourceExist(String resourceId) {
        QueryWrapper<TResources> wrapper = new QueryWrapper<>();
        wrapper.eq("resource_id",resourceId);
        int count = resourcesMapper.selectCount(wrapper);
        if(count>0){
            return true;
        }
        return false;
    }

    /**
     * 逻辑删除资源
     * @param resourceId
     */
    @Override
    public void deleteResourceById(String resourceId) {
        resourcesMapper.deleteResourceById(resourceId);
    }

    /**
     * 初始化主界面
     * @return
     */
    @Override
    public List<Map<String,Object>> initMainPage(String order) {
        if(StringUtils.isEmpty(order)){
            order = "created_at";
        }else if(order.equals("T")){
            order = "created_at";
        }else if(order.equals("C")){
            order = "click_count";
        }
        List<Map<String,Object>> list = new ArrayList<>();
        List<TBar> barList = barMapper.getBarListByType("L");
        for (TBar tBar : barList) {
            List<TResourcesVo> resourcesList = resourcesMapper.getResourcesList(tBar.getValue(), "", "", "", 0, 8,order);
            if(resourcesList.size()>0){
                Map<String,Object> map = new HashMap<>();
                map.put("title",tBar.getTitle());
                resourcesList.forEach(tResourcesVo -> {
                    String htmlString = tResourcesVo.getDescription();
                    String plainText = htmlString.replaceAll("\\<.*?\\>", "");
                    tResourcesVo.setDescription(plainText);
                });
                map.put("data",resourcesList);
                list.add(map);
            }
        }
        return list;
    }

    @Override
    public void addClikCount(String resourceId) {
        try{
            resourcesMapper.addClikCount(resourceId);
        }catch (Exception e){
            log.error("addClikCount报错！"+e.getMessage());
        }
    }


}
